package com.esfak47.mediafetcher.app.controller;

import com.esfak47.common.PageResult;
import com.esfak47.common.Result;
import com.esfak47.common.extension.URL;
import com.esfak47.common.job.Job;
import com.esfak47.common.job.JobManager;
import com.esfak47.mediafetcher.core.service.JobBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.esfak47.mediafetcher.core.constants.Constants.ServerOptCode.createJobFailed;
import static com.esfak47.mediafetcher.core.constants.Constants.ServerOptCode.submitJobFailed;

/**
 * @author tony
 */
@RestController
public class JobController {

    @Resource
    private JobManager jobManager;
    @Resource
    private JobBuilder jobBuilder;

    @GetMapping(value = "jobs")
    public Result<PageResult<Job>> getJob(int page, int pageSize) {
        PageResult<Job> jobs = jobManager.getJobs(page, pageSize);
        return Result.success(jobs);
    }

    @GetMapping(value = "jobs/{jobId}")
    public Result<Job> getJob(@PathVariable(value = "jobId") String jobId) {
        Job job = jobManager.getJob(jobId);
        return Result.success(job);
    }

    @PutMapping(value = "jobs/{jobId}")
    public Result<Boolean> cancelJob(@PathVariable(value = "jobId") String jobId) {
        Boolean be = jobManager.cancel(jobId);
        return Result.success(be);
    }

    @PostMapping(value = "jobs/create")
    public Result<String> createDownloadJob(@RequestBody Map<String, Object> input, HttpServletRequest request
    ) {

        HashMap<String, String> parameterMap = new HashMap<>();
        for (String k : input.keySet()) {
            parameterMap.put(k, input.get(k).toString());
        }
        URL url = new URL(parameterMap.get("type"), null, 0, parameterMap);
        Job job = jobBuilder.createJob(url);
        if (job != null) {
            final boolean submit = jobManager.submit(job);
            if (submit) {
                return Result.success(job.getId());
            }else {
                return Result.failWithReason(submitJobFailed);
            }
        }
        return Result.failWithReason(createJobFailed);

    }

}
